package com.sicheng.lc.周赛.分类.设计;

import java.util.HashMap;
import java.util.TreeSet;

/**
 * @author zsc
 * @version 1.0
 * @date 2022/7/24 11:07
 */
public class 设计食物评分系统 {
    //https://leetcode.cn/problems/design-a-food-rating-system/
    class FoodRatings {
        HashMap<String, TreeSet<String>> cache = new HashMap<>();
        int[] ratings;
        String[] foods;
        String[] cuisines;
        HashMap<String, Integer> map = new HashMap<>();

        public FoodRatings(String[] foods, String[] cuisines, int[] ratings) {
            this.foods = foods;
            this.ratings = ratings;
            this.cuisines = cuisines;
            for (int i = 0; i < foods.length; i++) {
                map.put(foods[i], i);
            }
            for (int i = 0; i < foods.length; i++) {
                cache.computeIfAbsent(cuisines[i],
                                k -> new TreeSet<>((a, b) -> {
                                    int l = map.get(a);
                                    int p = map.get(b);
                                    if (this.ratings[l] != this.ratings[p])
                                        return this.ratings[p] - this.ratings[l];
                                    return a.compareTo(b);
                                }))
                        .add(foods[i]);
            }
        }

        public void changeRating(String food, int newRating) {
            int i = map.get(food);
            TreeSet<String> treeSet = cache.get(cuisines[i]);
            treeSet.remove(food);
            ratings[i] = newRating;
            treeSet.add(food);
        }

        public String highestRated(String cuisine) {
            return cache.get(cuisine).first();
        }
    }
}
